package cn.bb.gulimall.product.service.impl;

import cn.bb.common.utils.PageUtils;
import cn.bb.common.utils.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.bb.gulimall.product.dao.CategoryDao;
import cn.bb.gulimall.product.entity.CategoryEntity;
import cn.bb.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        List<CategoryEntity> collect = categoryEntities.stream()
                //过滤
                .filter(categories ->
                        //当他的父id为0  证明是一级分类
                        categories.getParentCid() == 0
                )
                .map((menu)->{
                    //定义获取子菜单方法 这能够递归找子菜单的子菜单
                    menu.setChildren(getChildren(menu,categoryEntities));
                    return menu;
                })
                //再根据sort降序排列
                .sorted((menu1,munu2)->{
                    return menu1.getSort()-munu2.getSort();
                })
                //转化为集合返回
                .collect(Collectors.toList());


        return collect;
    }

    @Override
    public void removeLogicByIds(List<Long> asList) {
        //TODO 未完 有引用的 不能删 需先判断
        baseMapper.deleteBatchIds(asList);
    }

    /**
     *
     * @param root  某个父级分类
     * @param allCategories 所有商品
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> allCategories) {
        List<CategoryEntity> children = allCategories.stream()
                .filter(categories -> {
                    //从所有商品中找出和父级分类和root相同的商品 即为我们要找的子菜单集合
                    return categories.getParentCid().equals(root.getCatId());
                })
                .map((menu) -> {
                    //递归找下一个符合条件的子菜单并设置进children里
                    menu.setChildren(getChildren(menu, allCategories));
                    return menu;
                })
                //再次排序
                .sorted((menu1, menu2) -> {
                    return menu1.getSort() - menu2.getSort();
                })
                //最终转为list集合
                .collect(Collectors.toList());
        return children;
    }

}